<template>
  <div class="container">
    资源名称：
    <el-input v-model="query.name" placeholder="请输入资源名称" class="item" style="width: 200px"></el-input>
    类型：
    <el-select v-model="query.type" placeholder="请选择类型" class="item" style="width: 200px">
      <el-option label="" value=""></el-option>
      <el-option label="技术" value="TECH"></el-option>
      <el-option label="英语" value="EN"></el-option>
    </el-select>
    <el-button type="primary" @click="search" class="item">查询</el-button>
    <el-button type="primary" @click="openDialog" class="item">新增</el-button>
  </div>
  <RocList :data="table.data"
           :columns="table.columns"
           :pageSize="table.pageSize"
           :total="table.total"
           @pageChange="pageChange"
           @pageSizeChange="pageSizeChange"
           @edit="edit"
           @view="view"
           @delete="handleDelete">
  </RocList>

  <el-dialog title="资源" v-model="dialogFormVisible" width="500px">
    <el-form :model="form" ref="resourceForm">
      <el-form-item label="分类">
        <el-select v-model="form.type" placeholder="请选择资源分类">
          <el-option label="技术" value="TECH"></el-option>
          <el-option label="英语" value="EN"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="上传" prop="file">
        <el-upload
            class="upload-demo"
            ref="uploadFile"
            limit="1"
            action="http://nas.peng.cafe:28006/upload/file"
            :data="extraData"
            :headers="formHeader"
            :before-upload="uploadValidation"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="uploadFileSuccess"
            :file-list="fileList"
            :auto-upload="false">
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm()">提 交</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import {ref, reactive, onMounted, getCurrentInstance} from 'vue'
import {ElMessage} from 'element-plus';
import RocList from '@/components/RocList';
import Url from "@/consts/Url";
import {useRouter} from 'vue-router';
import {RESPONSE_ERROR_CODE} from '@/consts/Codes'
import UserToken from "@/user/UserToken";

const router = useRouter();
const {proxy} = getCurrentInstance();

const table = reactive({
  total: 1,
  data: [],
  currentPage: 1,
  rows: 10,
  columns: [
    {prop: 'name', label: '资源名'},
    {prop: 'recallDate', label: '回顾时间'},
    {prop: 'type', label: '类型'}
  ]
});

const query = reactive({
  name: '',
  type: ''
});


const dialogFormVisible = ref(false);
const resourceForm = ref(null);


const loadTableData = async () => {
  try {
    let params = {
      page: table.currentPage,
      rows: table.rows,
      name: query.name,
      type: query.type,
      state: 1
    };
    const response = await proxy.$request.get(Url.RECALL.RECALL_LIST.value, params);
    if (response.code === RESPONSE_ERROR_CODE.NO_LOGIN.value) {
      ElMessage.warning(response.message);
      router.push("/login");
    }
    table.data = response.data;
  } catch (error) {
    console.error('Error loading table data:', error);
  }
};

const loadTableCount = async () => {
  try {
    let params = {
      name: query.name,
      type: query.type,
      state: 1
    };
    const response = await proxy.$request.get(Url.RECALL.RECALL_LIST_COUNT.value, params);
    table.total = response.data;
  } catch (error) {
    console.error('Error loading table count:', error);
  }
};

onMounted(() => {
  loadTableData();
  loadTableCount();
});

function pageChange(page) {
  table.currentPage = page;
  loadTableData();
}

function pageSizeChange(pageSize) {
  table.rows = pageSize;
  loadTableData();
}

function edit(id) {
  ElMessage.info("Edit click, id=" + id);
}


async function handleDelete(id) {
  try {
    let params = {id: id};
    const response = await proxy.$request.get(Url.RECALL.RECALL_DELETE.value, params);
    if (response.code === RESPONSE_ERROR_CODE.SUCCESS.value) {
      ElMessage.success("删除成功");
      loadTableData();
      loadTableCount();
    }
  } catch (error) {
    console.error('Error deleting data:', error);
  }
}

function search() {
  loadTableData();
  loadTableCount();
}

function openDialog() {
  dialogFormVisible.value = true;
}

function view(row){
  console.log(JSON.stringify(row));
  window.open(row.path, '_blank');
}

//以下是提交表单
const form = ref({
  type: ''
});
const uploadUrl = ref(Url.RECALL.RECALL_ADD.value);
const extraData = ref({
  type: ''
});
const uploadFile = ref(null);

const formHeader = ref({
  token: UserToken.token()
});

const uploadValidation = () => {
  if (form.value.type === "") {
    ElMessage.warning("请选择资源类型");
    return false;
  }

  return true;
}
const submitForm = () => {
  if (uploadValidation()) {
    extraData.value.type = form.value.type;
    console.log("extraData : ", extraData.value.type);
    uploadFile.value.submit();
  }
}

const uploadFileSuccess = (response) => {
  console.log("response: " + JSON.stringify(response));
  if (response.code === RESPONSE_ERROR_CODE.SUCCESS.value) {
    ElMessage.success("上传成功");
    uploadFile.value.clearFiles();
    form.value.type="";
    dialogFormVisible.value = false;
    loadTableData();
    loadTableCount();
  }
}


</script>

<style scoped>
.container {
  display: flex;
  justify-content: left;
  align-items: center;
}

.item {
  margin: 10px;
}

.form-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: left;
}
</style>
